package com.cqupt.slewing

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.cqupt.slewing.room.ItemViewModel
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private lateinit var myViewModel: MyViewModel
    private lateinit var itemViewModel: ItemViewModel
    private lateinit var shp: SharedPreferences

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportActionBar?.hide()
        /* 自适应status bar */
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = resources.getColor(R.color.black)

        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController
        findViewById<BottomNavigationView>(R.id.bottom_nav_view)
            .setupWithNavController(navController)

        itemViewModel = ViewModelProvider(this)[ItemViewModel::class.java]
        myViewModel = ViewModelProvider(this)[MyViewModel::class.java]
        shp = this.getSharedPreferences("MyData", Context.MODE_PRIVATE)
    }

    override fun onStart() {
        super.onStart()

        lifecycleScope.launch(IO) {
            itemViewModel.clear()
            val items = myViewModel.getAllDevice()
            val macList = arrayListOf<String>()

            for (item in items) {
                itemViewModel.insert(item)
                macList.add(item.macID)
            }
            Intent(this@MainActivity, MyService::class.java).also {
                it.putExtra("session", shp.getString("session", ""))
                it.putStringArrayListExtra("mac", macList)
                startService(it)
            }
        }
    }

}